﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using 模板.ViewModel;

namespace 模板
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }

        /// <summary>
        /// 把所有控件遍历并显示到控件中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = new TreeViewItem() { Header = "逻辑树根" };

            LogicalTree(item, this);

            _TreeView.Items.Add(item);
        }


        /// <summary>
        /// 遍历控件的逻辑树
        /// </summary>
        /// <param name="item"></param>
        /// <param name="element"></param>
        private void LogicalTree(TreeViewItem item, object element)
        {
            if (!(element is DependencyObject)) return;

            TreeViewItem treeViewItem = new TreeViewItem { Header = element.GetType().Name };

            item.Items.Add(treeViewItem);

            var elements = LogicalTreeHelper.GetChildren(element as DependencyObject);

            foreach (object child in elements)
            {
                LogicalTree(treeViewItem, child);
            }

        }


        /// <summary>
        /// 获取控件的可视化树
        /// </summary>
        /// <param name="item"></param>
        /// <param name="element"></param>
        private void VisualTree(TreeViewItem item, object element)
        {
            if (!(element is DependencyObject)) return;

            TreeViewItem treeViewItem = new TreeViewItem { Header = element.GetType().Name };

            item.Items.Add(treeViewItem);

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element as DependencyObject); i++)
            {
                VisualTree(treeViewItem, VisualTreeHelper.GetChild(element as DependencyObject, i));
            }
        }



        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = new TreeViewItem() { Header = "可视化树根" };

            VisualTree(item, this);

            _TreeView2.Items.Add(item);
        }
    }
}